import marimo

__generated_with = "0.9.27"
app = marimo.App(width="medium")


@app.cell
def __():
    from random import randint



    # 骰子对象
    class Die:

        def __init__(self, num_sides=6):
            self.num_sides = num_sides

        def roll(self):
            return randint(1, self.num_sides)



    return Die, randint


@app.cell
def __(Die):
    # 骰子每次的值

    die_1 = Die()

    throw_times = 1000

    results = []

    for roll_num in range(throw_times):
        result = die_1.roll()
        results.append(result)

    results

    return die_1, result, results, roll_num, throw_times


@app.cell
def __(die_1, results):
    # 6个面出现的频率

    freqs = []

    for value in range(1, die_1.num_sides+1):

        # 统计results,1-6出现的次数
        freq = results.count(value)
        freqs.append(freq)

    freqs
    return freq, freqs, value


@app.cell
def __(die_1, freqs, throw_times):
    # 绘制交互图


    from plotly.graph_objs import Bar, Layout
    from plotly import offline


    # plotly不能接受range,需转为list
    x_values = list(range(1, die_1.num_sides+1))

    # 使用Bar类,data可能包含多个元素,此处必须是list
    data = [Bar(x=x_values, y=freqs)]

    x_axis_config = {'title': '结果'}
    y_axis_config = {'title': '结果的频率'}

    # 使用Layout类
    my_layout = Layout(title=f'掷一个D6 {throw_times}次的结果', xaxis=x_axis_config, yaxis=y_axis_config)
    offline.plot({'data': data, 'layout': my_layout}, filename='d6.html')
    return (
        Bar,
        Layout,
        data,
        my_layout,
        offline,
        x_axis_config,
        x_values,
        y_axis_config,
    )


@app.cell
def __(Bar, Die, Layout, offline):
    # 2个骰子的概率

    _die_1 = Die()
    _die_2 = Die()


    _throw_times = 1000

    _results = []

    for _roll_num in range(_throw_times):

        # 计算2个骰子的点数
        _result = _die_1.roll() + _die_2.roll()
        _results.append(_result)




    _freqs = []

    _max_result = _die_1.num_sides + _die_2.num_sides
    for _value in range(2, _max_result+1):

        # 统计results,1-6出现的次数
        _freq = _results.count(_value)
        _freqs.append(_freq)


    # plotly不能接受range,需转为list
    _x_values = list(range(1,  _max_result+1))

    # 使用Bar类,data可能包含多个元素,此处必须是list
    _data = [Bar(x=_x_values, y=_freqs)]

    # 'dtick': 1,指定x轴间距是1
    _x_axis_config = {'title': '结果', 'dtick': 1}
    _y_axis_config = {'title': '结果的频率'}

    # 使用Layout类
    _my_layout = Layout(title=f'掷两个D6 {_throw_times}次的结果', xaxis=_x_axis_config, yaxis=_y_axis_config)
    offline.plot({'data': _data, 'layout': _my_layout}, filename='d6_d6.html')

    return


if __name__ == "__main__":
    app.run()
